#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>

#include "cJSON.h"
#include "client_sq.h"


int json_pack(struct client_data str,char *jsonout,int len)
{
        cJSON *json = NULL;

	if(!jsonout || len <= 0)
	{
		return -1;
	}

        json = cJSON_CreateObject();
        cJSON_AddStringToObject(json,"id",str.id);
        cJSON_AddStringToObject(json,"temp",str.temp);
        cJSON_AddStringToObject(json,"time",str.time);

        strncpy(jsonout,cJSON_Print(json),len-1);
        cJSON_Delete(json);
	return 0;
}

int json_unpack(char *jsonin,struct client_data *str)
{

        cJSON *json = NULL;
        cJSON *json_id = NULL;
        cJSON *json_temp = NULL;
        cJSON *json_time = NULL;

	if(!jsonin || !str)
	{
		return -1;
	}

        json = cJSON_Parse(jsonin);
        if(!json)
        {
                printf("Error:%s\n",strerror(errno));
                return -2;
        }
        else
        {
                json_id = cJSON_GetObjectItem(json,"id");
                json_temp = cJSON_GetObjectItem(json,"temp");
                json_time = cJSON_GetObjectItem(json,"time");
        }
        strcpy(str->id,json_id->valuestring);
        strcpy(str->temp,json_temp->valuestring);
        strcpy(str->time,json_time->valuestring);
        return 0;

}

